<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
  import echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from './resize'
  import { req } from '../../../../api/base/BaseApi'
  // import index from './index'

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '100%'
      },
      toStrain: {
        type: Array,
        default: ['测点1']
      },
      option: {
        backgroundColor: 'rgba(34,34,34,0.9)'
      }
    },
    data() {
      return {
        chart: null,
        reqTimer: null,
        setTimer: null,
        xTime: [],
        xTimeQueue: [],
        strainQueues: {},
        strainData: {},
        seriesMaps: [],
        measurePoints: [],
        count: 0
      }
    },
    watch: {
      toStrain: function(newVal, oldVal) {
      },
      option() {
        this.setOption()
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.xTime = []
        this.xTimeQueue = []
        this.measurePoints = [ '测点']
        clearInterval(this.reqTimer)
        clearInterval(this.setTimer)
        // map 初始化
        this.strainQueues = new Map()
        this.strainData = new Map()
        for (let i = 0; i < this.measurePoints.length; i++) {
          const point = this.measurePoints[i]
          this.strainQueues.set(point, [])
          this.strainData.set(point, [])
        }
        this.getPrevChartData()
        // 折线图初始化
        setTimeout(() => {
          this.initChart()
          // 获取更新数据（定时器每 20 秒取一次，每次取 20 个数据）
          this.getChartData()
          this.reqTimer = setInterval(() => {
            this.getChartData()
          }, 20000)
          // 更新数据
          this.setTimer = setInterval(() => {
            this.setChartData()
          }, 1000)
        }, 1000)
      })
    },
    beforeDestroy() {
      this.chart.clear()
      clearInterval(this.reqTimer)
      clearInterval(this.setTimer)
    },
    methods: {
      getPrevChartData() {
        for (let i = 0; i < this.measurePoints.length; i++) {
          const point = this.measurePoints[i]
          req('/api/sys/auth/MG/preVibration/' + point, 'POST', '').then(response => {
            const tempList = response.data
            for (let j = 0; j < tempList.length; j++) {
              const e = {
                name: tempList[j].timestamp,
                value: tempList[j].value
              }
              this.strainQueues.get(point).push(e)
              if (i <= 0) {
                this.xTimeQueue.push(tempList[j].time)
              }
            }
          }).catch(() => console.log('page request error'))
        }
      },
      getChartData() {
        for (let i = 0; i < this.measurePoints.length; i++) {
          const point = this.measurePoints[i]
          req('/api/sys/auth/MG/vibration/' + point, 'POST', '').then(response => {
            const tempList = response.data
            for (let j = 0; j < tempList.length; j++) {
              const e = {
                name: tempList[j].timestamp,
                value: tempList[j].value
              }
              this.strainQueues.get(point).push(e)
              if (i <= 0) {
                this.xTimeQueue.push(tempList[j].time)
              }
            }
          }).catch(() => console.log('page request error'))
        }
      },
      setChartData() {
        const time = this.xTimeQueue.shift()
        this.xTime.shift()
        this.xTime.push(time)
        for (let i = 0; i < this.measurePoints.length; i++) {
          const point = this.measurePoints[i]
          const t = this.strainQueues.get(point).shift()
          this.strainData.get(point).shift()
          this.strainData.get(point).push(t)
        }
        this.$emit('func', this.strainData)
        // set series
        this.seriesMaps = []
        for (let i = 0; i < this.measurePoints.length; i++) {
          const point = this.measurePoints[i]
          const seriesMap = {
            name: point,
            type: 'line',
            smooth: true,
            data: this.strainData.get(point),
            markPoint: {
              data: [{
                name: '最大值',
                type: 'max'
              }, {
                name: '最小值',
                type: 'min'
              }]
            }
          }
          this.seriesMaps.push(seriesMap)
        }
        this.chart.setOption({
          xAxis: {
            data: this.xTime
          },
          series: this.seriesMaps
        })
      },
      setOption() {
        this.dom.setOption(this.option)
      },
      initChart() {
        // const len = this.measurePoints.length
        // for (let i = 0; i < len; i++) {
        //   const temperatureDataI = []
        //   const date = new Date()
        //   for (let j = 0; j < 60; j++) {
        //     const e = {
        //       name: date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(),
        //       value: 300
        //     }
        //     temperatureDataI.push(e)
        //   }
        //   this.temperatureData.set(this.measurePoints[i], temperatureDataI)
        // }
        // for (let j = 0; j < 60; j++) {
        //   this.xTime.push('0')
        // }
        for (let i = 0; i < 60; i++) {
          const time = this.xTimeQueue.shift()
          this.xTime.push(time)
          for (let j = 0; j < this.measurePoints.length; j++) {
            const point = this.measurePoints[j]
            const t = this.strainQueues.get(point).shift()
            this.strainData.get(point).push(t)
          }
        }
        this.$emit('func', this.strainData)
        this.seriesMaps = []
        for (let i = 0; i < this.measurePoints.length; i++) {
          const point = this.measurePoints[i]
          const seriesMap = {
            name: point,
            type: 'line',
            smooth: true,
            data: this.strainData.get(point)
          }
          this.seriesMaps.push(seriesMap)
        }
        if (this.chart != null) {
          this.chart.clear()
        }
        this.chart = echarts.init(this.$el, 'macarons')
        this.chart.setOption({
          backgroundColor: '#3A4057',
          title: {
            text: '高速轴齿轮X',
            left: '5%',
            top: '5%'
          },
          tooltip: {
            trigger: 'axis',
            formatter: function(params) {
              const param0 = params[0]
              const date = new Date(param0.name)
              let s = '日期：' + date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
              for (let i = 0; i < params.length; i++) {
                s += '<br/>' + params[i].seriesName + ': ' + params[i].value
              }
              return s
            },
            axisPointer: {
              animation: false
            }
          },
          legend: {
            right: '5%',
            top: '5%',
            data: this.measurePoints,
            textStyle: {
              color: '#ffffff'
            }
          },
          dataZoom: [
            {
              show: true,
              realtime: true,
              start: 0,
              end: 20
            }
          ],
          // 上下左右边距
          grid: {
            left: '8%',
            right: '8%',
            bottom: '10%',
            top: '20%'
          },
          xAxis: {
            type: 'category',
            name: '时间',
            boundaryGap: false,
            // splitLine: {
            //   show: false
            // },
            data: this.xTime
          },
          yAxis: {
            type: 'value',
            name: '数据值',
            boundaryGap: false,
            max: 2,
            min: -2
            // splitLine: {
            //   show: false
            // }
          },
          series: this.seriesMaps
        })
      }
    }
  }
</script>

<style scoped>

</style>
